package com.example.myapplication;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private EditText etUsername, etPassword;
    private CheckBox cbRememberPassword, cbAgreeTerms;
    private TextView tvRegister;
    private Button btnLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化视图
        etUsername = findViewById(R.id.editTextText);
        etPassword = findViewById(R.id.editTextTextPassword);
        cbRememberPassword = findViewById(R.id.checkBox);
        cbAgreeTerms = findViewById(R.id.checkBox2);
        tvRegister = findViewById(R.id.tv_info);
        btnLogin = findViewById(R.id.button);

        // 跳转到注册页面
        tvRegister.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, Register.class);
            startActivity(intent);
        });

        // 登录按钮点击事件
        btnLogin.setOnClickListener(v -> attemptLogin());

        // 检查是否记住密码
        checkRememberedCredentials();
    }

    private void attemptLogin() {
        // 重置错误状态
        etUsername.setError(null);
        etPassword.setError(null);

        // 获取用户输入
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        // 检查是否勾选了协议
        if (!cbAgreeTerms.isChecked()) {
            Toast.makeText(this, "请同意用户协议", Toast.LENGTH_SHORT).show();
            return; // 直接返回，不进行后续验证
        }

        // 验证输入
        boolean cancel = false;
        View focusView = null;

        if (TextUtils.isEmpty(username)) {
            etUsername.setError("请输入账号");
            focusView = etUsername;
            cancel = true;
        } else if (TextUtils.isEmpty(password)) {
            etPassword.setError("请输入密码");
            focusView = etPassword;
            cancel = true;
        }

        if (cancel) {
            // 只有当有错误时才请求焦点
            if (focusView != null) {
                focusView.requestFocus();
            }
            return; // 输入有误，返回
        }

        // 验证账号密码
        if (verifyCredentials(username, password)) {
            saveCredentialsIfRemembered(username, password);
            startActivity(new Intent(this, BookHomepage.class));
        } else {
            Toast.makeText(this, "账号或密码错误", Toast.LENGTH_SHORT).show();
        }
    }

    // 验证账号密码是否匹配
    private boolean verifyCredentials(String username, String password) {
        SharedPreferences sp = getSharedPreferences("accountpasswd", MODE_PRIVATE);
        String savedUsername = sp.getString("username", "");
        String savedPassword = sp.getString("password", "");
        return username.equals(savedUsername) && password.equals(savedPassword);
    }

    // 保存账号密码（如果勾选了记住密码）
    private void saveCredentialsIfRemembered(String username, String password) {
        SharedPreferences sp = getSharedPreferences("accountpasswd", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        if (cbRememberPassword.isChecked()) {
            editor.putString("username", username);
            editor.putString("password", password);
            editor.putBoolean("remember", true);
        } else {
//            editor.remove("password");
//            editor.remove("password");
            editor.putBoolean("remember", false);
        }
        editor.apply();
    }

    // 检查是否已记住密码
    private void checkRememberedCredentials() {
        SharedPreferences sp = getSharedPreferences("accountpasswd", MODE_PRIVATE);
        boolean remember = sp.getBoolean("remember", false);
        if (remember) {
            String savedUsername = sp.getString("username", "");
            String savedPassword = sp.getString("password", "");
            etUsername.setText(savedUsername);
            etPassword.setText(savedPassword);
            cbRememberPassword.setChecked(true);
        }
    }
}